package com.zhijian.medical.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhijian.medical.dao.local.RoutinePatientDiagnoseLatestMapper;
import com.zhijian.medical.entity.dto.PersonDto;
import com.zhijian.medical.entity.po.RoutinePatientDiagnoseLatest;
import com.zhijian.medical.holder.CurrentUserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class RoutinePatientDiagnoseLatestService {

    @Autowired
    RoutinePatientDiagnoseLatestMapper routinePatientDiagnoseLatestMapper;

    /**
     * 添加个人的最新查看的记录
     * @param patientId 病人ID
     */
    public void handlePatient(Long patientId){
        RoutinePatientDiagnoseLatest routinePatientDiagnoseLatest = new RoutinePatientDiagnoseLatest();
        routinePatientDiagnoseLatest.setPatientId(patientId);
        handlePatient(routinePatientDiagnoseLatest);
    }

    public void handlePatient(RoutinePatientDiagnoseLatest routinePatientDiagnoseLatest){
        PersonDto personDto = CurrentUserHolder.getUser();
        QueryWrapper<RoutinePatientDiagnoseLatest> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", personDto.getId());
        queryWrapper.eq("patient_id",  routinePatientDiagnoseLatest.getPatientId());
        RoutinePatientDiagnoseLatest oldOne = routinePatientDiagnoseLatestMapper.selectOne(queryWrapper);
        Date now = new Date();
        if (oldOne == null){
            routinePatientDiagnoseLatest.setUserId(personDto.getId());
            routinePatientDiagnoseLatest.setLatestTime(now);
            routinePatientDiagnoseLatestMapper.insert(routinePatientDiagnoseLatest);
        }else {
            RoutinePatientDiagnoseLatest upd = new RoutinePatientDiagnoseLatest();
            upd.setLatestTime(now);
            upd.setId(oldOne.getId());
            routinePatientDiagnoseLatestMapper.updateById(upd);
        }
    }
}
